//
//  PaymentPageVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/5/15.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "PaymentPageVC.h"
#import "PaymentCell.h"
#import "AccountTicketVC.h"
#import "ContactService.h"
#import "IAPManager.h"
#import "PayHelpVC.h"
#import "WXAlertVC.h"
#import <UILabel+YBAttributeTextTapAction.h>
#import <WXApi.h>

@interface PaymentPageVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIImageView *cityTourImageView;

@property (weak, nonatomic) IBOutlet UILabel *tourNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UILabel *CouponLabel;

@property (weak, nonatomic) IBOutlet UIButton *confirmPaymentBtn;

@property (weak, nonatomic) IBOutlet UILabel *payMentLabel;

@property (weak, nonatomic) IBOutlet UITableView *payMentWaysTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navigationH;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottomSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *PayMentViewH;
@property (weak, nonatomic) IBOutlet UIView *couponView;
@property (weak, nonatomic) IBOutlet UILabel *couponText;

@property (nonatomic, strong) Coupon *coupon;
@property (nonatomic, strong) NSMutableArray *couponArray;

@property (nonatomic,strong)NSIndexPath  * currentIndexPath;

@property (nonatomic, strong)NSMutableArray * dataSource;


@property (weak, nonatomic) IBOutlet UILabel *payHelpTitle;
@property (weak, nonatomic) IBOutlet UILabel *payHelpDes1Label;
@property (weak, nonatomic) IBOutlet UILabel *payHelpDes2Label;
@property (weak, nonatomic) IBOutlet UILabel *payHelpDes3Label;


@property (weak, nonatomic) IBOutlet UILabel *orderDescribeLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderNOLabel;
@property (weak, nonatomic) IBOutlet UIButton *funCopyBtn;

@property (weak, nonatomic) IBOutlet UIView *helpView;

@end

@implementation PaymentPageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self setupData];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self reloadPriceView];
    
    [MobClick beginLogPageView:@"10"];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [MobClick endLogPageView:@"10"];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

- (void)setupUI {
    
    
    self.orderDescribeLabel.text = [NSString stringWithFormat:@"%@：",MYLocalizedString(@"MYORDER_ORDERNO", nil)];
    [self.funCopyBtn setTitle:MYLocalizedString(@"CONTACT_COPY", nil) forState:UIControlStateNormal];
    
    self.navigationH.constant = kNavigationBarHeight + 10;
    
    if (ISiPhoneX) {
        self.toBottomSpace.constant = 34;
    }
    self.couponText.text = MYLocalizedString(@"PAYORDER_VOUCHER", nil);
    self.view.backgroundColor = kBGColor;
    self.confirmPaymentBtn.backgroundColor = kThemeColor;
    [self.confirmPaymentBtn setTitle:MYLocalizedString(@"PAYORDER_PAY", nil) forState:UIControlStateNormal];
    self.title = MYLocalizedString(@"PAYORDER_TITLE", nil);
    
    [self.payMentWaysTableView registerNib:[UINib nibWithNibName:@"PaymentCell" bundle:nil] forCellReuseIdentifier:@"PaymentCell"];
    [self.payMentWaysTableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"UITableViewHeaderFooterView"];
    self.payMentWaysTableView.scrollEnabled = NO;
    
    [self rightBarButton:MYLocalizedString(@"PUBLIC_CANCEL", nil) color:[UIColor whiteColor] selector:@selector(backAction)];
    
    if (self.pageType == 0) {
        [self.payMentWaysTableView removeFromSuperview];
    }
    
    if ([[UserManager sharedManager].user.role integerValue] != UserRolesTypeLow && [UserManager sharedManager].token) {
        self.couponView.hidden = NO;
        [self.couponView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseCouponAction)]];
    } else {
        
        self.couponView.hidden = YES;
    }
    
    NSString *contrycode = [AppManager sharedManager].currentCountryCode;
    
    if (![[contrycode lowercaseStringWithLocale:[NSLocale currentLocale]] containsString:@"cn"]) {
        self.helpView.hidden = YES;
        return;
    }
    
    self.payHelpTitle.text = MYLocalizedString(@"PAYORDER_HELP_TITLE", nil);
    self.payHelpDes1Label.text = MYLocalizedString(@"PAYORDER_HELP_DES1", nil);
    
    NSString *des2str1 = MYLocalizedString(@"PAYORDER_HELP_DES21", nil);
    NSString *des2str2 = MYLocalizedString(@"PAYORDER_HELP_DES22", nil);
    
    
    NSMutableAttributedString *des2Text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",des2str1,des2str2]];
    
    [des2Text addAttribute:NSForegroundColorAttributeName value:kThemeColor range:NSMakeRange(des2str1.length,  des2str2.length)];
    
    self.payHelpDes2Label.attributedText = des2Text;
    
    @weakify(self);
    [self.payHelpDes2Label yb_addAttributeTapActionWithStrings:@[des2str2] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        @strongify(self);
        
        PayHelpVC *webVC = [PayHelpVC new];
        webVC.url = @"https://mp.weixin.qq.com/s/y58rnOQSlMFHSNGuDdKdQQ";
        webVC.title = des2str2;
        [self.navigationController pushViewController:webVC animated:YES];
        self.payHelpDes2Label.enabledTapEffect = NO;
        
    }];
    
    NSString *des3str1 = MYLocalizedString(@"PAYORDER_HELP_DES31", nil);
    NSString *des3str2 = MYLocalizedString(@"PAYORDER_HELP_DES32", nil);
    
    
    NSMutableAttributedString *des3Text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ImGuider%@",des3str1,des3str2]];
    
    [des3Text addAttribute:NSForegroundColorAttributeName value:kThemeColor range:NSMakeRange(des3str1.length, 8)];
    
    self.payHelpDes3Label.attributedText = des3Text;
    
    [self.payHelpDes3Label yb_addAttributeTapActionWithStrings:@[@"ImGuider"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:@"ImGuider"];
        
        WXAlertVC *alertVC = [WXAlertVC new];

        [alertVC showWithVC:self];
    }];
}

- (void)setupData {
    
    [self.cityTourImageView setImageURL:[NSURL URLWithString:self.lineModel.pictures] placeholderImage:[UIImage imageNamed:@"placeholder_squ"]];
    self.tourNameLabel.text = self.lineModel.linename;
    self.priceLabel.text = self.lineModel.price;
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    
    dispatch_group_t net_group = dispatch_group_create();
    dispatch_group_enter(net_group);
    
    @weakify(self);
    [NetAPIManager getMycouponsWithLineid:self.lineModel.lineid Block:^(NSArray<Coupon *> *couponArray, NSError *error) {
        @strongify(self);
        dispatch_group_leave(net_group);
        
        self.couponArray = [NSMutableArray arrayWithArray:couponArray];
        [self reloadPriceView];
    }];
    dispatch_group_enter(net_group);
    [NetAPIManager preorderOrderWithLineID:self.lineModel.lineid block:^(NSString *result, NSError *error) {
        @strongify(self);
        dispatch_group_leave(net_group);
        if (result) {
            self.orderNOLabel.text = result;
        }
    }];
    
    dispatch_group_notify(net_group, dispatch_get_main_queue(), ^{
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
    });
}

- (void)backAction {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [MobClick event:@"10_1_2"];
}


- (IBAction)copyOrderNoAction:(id)sender {
    
    NSString *contact = self.orderNOLabel.text;
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = contact;
    
    [IGUtils showToast:MYLocalizedString(@"CONTACT_COPY_SUCCESS", nil)];
}

- (void)chooseCouponAction {
    
    AccountTicketVC *ticketVC = [IGUtils loadViewController:@"AccountTicketVC" storyboard:@"Account"];
    
    ticketVC.pageType = 1;
    ticketVC.dataSource = self.couponArray;
    ticketVC.delegate = self;
    
    [self.navigationController pushViewController:ticketVC animated:YES];
    
    [MobClick event:@"10_1_3"];
}

#pragma mark -AccountTicketVCDelegagte
- (void)selectCoupon:(Coupon *)coupon {
    
    self.coupon = coupon;
    [self reloadPriceView];
}

- (void)reloadPriceView {
    
    NSDictionary *dict = self.dataSource[self.currentIndexPath.row];
    
    NSString *price = self.lineModel.price;
    if (self.couponArray.count == 0) {
        
        self.CouponLabel.text = MYLocalizedString(@"PAYORDER_NONE", nil);
        self.CouponLabel.textColor = kContentColor;
    } else {
        self.CouponLabel.textColor = kThemeColor;
    }
    
    if (self.coupon) {
        self.CouponLabel.textColor = kThemeColor;
        self.CouponLabel.text = [NSString stringWithFormat:@"%@%@",self.coupon.infos[@"big"],self.coupon.infos[@"middle"]];
        price = self.coupon.infos[@"feestring"];
    } else {
        self.CouponLabel.text = [NSString localizedStringWithFormat:MYLocalizedString(@"PAYORDER_TOTAL", nil),@(self.couponArray.count)];
    }
    
    self.payMentLabel.textColor = kThemeColor;
    if (self.pageType == 0) {
        self.payMentLabel.text = price;
    } else {
        self.payMentLabel.text = [NSString stringWithFormat:@"%@：%@",dict[@"payMentWay"],price];
    }
}

- (NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        
        if (self.pageType == 0) {
            
            _dataSource = [NSMutableArray arrayWithArray:@[@{@"type":@(PayTypeIAP)}]];
        } else {
            
            _dataSource = [NSMutableArray arrayWithArray:@[@{@"icon":@"wepay",@"payMentWay":@"微信支付",@"type":@(PayTypeWX)},@{@"icon":@"alipay",@"payMentWay":@"支付宝",@"type":@(PayTypeAlipay)},@{@"icon":@"palpay",@"payMentWay":@"Paypal",@"type":@(PayTypePaypal)}]];
        }
    }
    
    return _dataSource;
}

- (IBAction)confirmPaymentBtnClicked:(UIButton *)sender {
    
    [MobClick event:@"10_1_4"];
    
//    NSDictionary * dict = self.dataSource[self.currentIndexPath.row];
//
//    PayType type = [dict[@"type"] integerValue];
    
    [ActivityIndicatorView showHUDAddedTo:self.view.window];
    @weakify(self);
    
    [[IAPManager sharedManager] paymentID:self.lineModel.lineid couponid:self.coupon.couponid ordernumber:self.orderNOLabel.text andBlock:^(NSString *result, NSError *error) {
        
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view.window];
        
        if (!error) {
            [IGUtils showToast:MYLocalizedString(@"PAYORDER_SUCCESS", nil)];
            
            if ([_delegate respondsToSelector:@selector(paySuccessCallback)]) {
                [_delegate paySuccessCallback];
            }
            [self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        
        if (error.code == PAY_FILEDCOED_SERVERERROR) {
            
            [IGAlertView alertWithTitle:MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil) message:MYLocalizedString(@"PAYORDER_FAILED_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYORDER_CONTACTSTAFF", nil) commit:^{
                UIViewController *contactService = [IGUtils loadViewController:@"ContactService" storyboard:@"Account"];
                [self.navigationController pushViewController:contactService animated:YES];
            } cancel:nil];
            
        } else {
            
            [IGUtils showToast:[IGUtils tipFromError:error]];
        }
        return;
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.pageType == 0) {
        
        return 0;
    }
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PaymentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PaymentCell"];
    
    NSDictionary * dict = self.dataSource[indexPath.row];
    
    if (indexPath.row == 0) {
        self.currentIndexPath = indexPath;
        cell.select = YES;
    }
    [cell configDataWithDict:dict];
    
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"UITableViewHeaderFooterView"];
    headerView.textLabel.text = [NSString stringWithFormat:@"支付方式"];
    headerView.textLabel.font = [UIFont systemFontOfSize:18];
    headerView.textLabel.textColor = [UIColor lightGrayColor];
    headerView.contentView.backgroundColor = [UIColor whiteColor];
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, SCREEN_WIDTH, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:0.7];
    [headerView addSubview:lineView];
    return headerView;
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.currentIndexPath.row == indexPath.row) {
        return;
    }
    PaymentCell * selecteCell = [tableView cellForRowAtIndexPath:self.currentIndexPath];
    selecteCell.select = NO;
    PaymentCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.select = YES;
    self.currentIndexPath = indexPath;
    [self reloadPriceView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
